package com.atguigu.seckill.interceptor;

import com.atguigu.common.Const.OauthConst;
import com.atguigu.common.vo.MemberEntityVo;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class MySecKillInterceptor implements HandlerInterceptor {
    //同一个线程间共享数据
    public static ThreadLocal<MemberEntityVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
//        boolean match = pathMatcher.match("/kill", requestURI);
        boolean match = pathMatcher.match("/seckill/**", requestURI);
        //如果是秒杀的请求，那么去判断一下是否登录
//        if (match) {
//            //session中获取登录后的用户信息
//            MemberEntityVo memberEntityVo = (MemberEntityVo) request.getSession().getAttribute(OauthConst.LOGIN_SESSION_KEY);
//            System.out.println("登录的用户:"+memberEntityVo);
//            //已经登陆过了
//            if (memberEntityVo != null) {
//                threadLocal.set(memberEntityVo);
//                return true;
//            } else {
//                request.getSession().setAttribute("errorMsg", "请先登录");
//                //没有登录过，跳转到登录页面
//                response.sendRedirect("http://auth.gulimall.com/login.html");
//                return false;
//            }
//            //其他请求直接放行
//        } else {
//            return true;
//        }
        Object attribute = request.getSession().getAttribute(OauthConst.LOGIN_SESSION_KEY);
        MemberEntityVo memberEntityVo = (MemberEntityVo) request.getSession().getAttribute(OauthConst.LOGIN_SESSION_KEY);
        System.out.println("登录的用户:" + memberEntityVo);
        //已经登陆过了
        if (memberEntityVo != null) {
            threadLocal.set(memberEntityVo);
        }
        return true;

    }
}
